<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/26
 * Time: 9:44
 */

namespace common\business\mdm;


use common\business\DbHandler;
use common\business\department\DepartmentApiHandler;
use common\business\kingdee\OrgAdminApiHandler;
use common\consts\MdmConsts;
use common\helpers\DbHelper;
use common\helpers\StringUtil;
use common\models\Department;
use common\models\kingdee\OrgAdmin;
use common\models\kingdee\Person;
use common\models\mdm\MdmOrg;
use common\result\ActionResult;
use yii\db\Query;

class MdmOrgService extends DbHandler
{
    /**按照姓名查找法人代表的id
     * @param $name
     * @return string
     */
    protected function findFrdbIdByName($name){
        $count = Person::find()->andFilterWhere([
            'FNAME_L2' => $name,
        ])->count();
        //如果没查到或者查到重名的人，则返回空
        if ($count != 1)
            return null;
        $personInDb = Person::findOne([
            'FNAME_L2' => $name,
        ]);
        return $personInDb->FID;
    }
    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalResult = new ActionResult();

        $db = MdmOrg::getDb();
        DbHelper::set_oracle_nls_timestamp_format();

        $query = (new Query())->from('MDM_ORG MO')
            ->leftJoin('MDM_ORG PMO', 'PMO.PK_MDM_ORG = MO.VVDEF25')
            ->select([
                'bill_code' => 'MO.BILLCODE',//主数据序号
                'pk' => 'MO.PK_MDM_ORG',//组织主数据主键
                'org_name' => 'MO.ORGNAME',//组织名称
                'parent_pk' => 'PMO.PK_ORG',//上级组织主数据主键
                'parent_org_name' => 'PMO.ORGNAME',//上级组织名称
                'yyzz_code' => 'MO.YYZZCODE',//营业执照号
                'social_union_code' => 'MO.DSDJCODE', //统一信用代码
                'start_date' => 'to_char(to_timestamp(substr(MO.STARTDATE, 0, 10) , \'yyyy-MM-dd\'), \'yyyy-MM-dd\')',//
                'end_date' => 'to_char(to_timestamp(substr(MO.ENDDATE, 0, 10) , \'yyyy-MM-dd\'), \'yyyy-MM-dd\')',//
                'address' => 'MO.TXADRESS',//通讯地址
                'zip_code' => 'MO.ZIPCODE',//邮政编码
                'phone' => 'MO.PHONE',
                'frdb' => 'MO.FRDBPOP', //法人代表
                'is_virtual' => 'MO.ISVIRTUAL', //是否虚拟组织
                'is_hr_org' => 'MO.BDEF4', //通过该字段判断是否接收该组织
            ]);
        $query->andFilterWhere([
            'MO.BDEF4' => MdmConsts::YES,
        ]);
        $query->orderBy([
            'MO.PK_ORG' => SORT_ASC,
        ]);

        $totalCount = $query->count('*', $db);

        $offset = 0;
        $pageSize = 100;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $org){
                $newOrgAdmin = new OrgAdmin();
                $newOrgAdmin->FBASEDUTY_L2 = $org['bill_code'];
                $newOrgAdmin->FNAME_L2 = $org['org_name'];
                $newOrgAdmin->FISJURIDICALCOMPANY = $org['is_virtual'] == MdmConsts::YES ? 1: 0;
                $frdbId = $this->findFrdbIdByName($org['frdb']);
                if (!StringUtil::isNullOrWhiteSpace($frdbId)){
                    $newOrgAdmin->FJURIDICALPERSONID = $frdbId;
                }
                $newOrgAdmin->FRESERVEFIELDSECOND = $org['social_union_code'];
                $newOrgAdmin->FEFFDT = $org['start_date'];
                $newOrgAdmin->FLEFFDT = $org['end_date'];
                $newOrgAdmin->FADMINADDRESS_L2 = $org['address'];
                $newOrgAdmin->FZIPCODE = $org['zip_code'];
                $newOrgAdmin->FPHONENUMBER = $org['phone'];

                $orgAdminInDb = OrgAdmin::findOne([
                    'FBASEDUTY_L2' => $newOrgAdmin->FBASEDUTY_L2,
                ]);

                $api = new OrgAdminApiHandler();
                if (!$orgAdminInDb){
//                    暂时不要程序自己加组织
//                    $totalResult->addSubResult($api->createOrgAdmin($newOrgAdmin));
                    $skipMsg = sprintf('skip to create OrgAdmin : %s', $newOrgAdmin->FNAME_L2);
                    $totalResult->addSubResult(new ActionResult(true, $skipMsg, true));
                }
                else {
                    if (StringUtil::isNullOrWhiteSpace($newOrgAdmin->FEFFDT)){
                        $newOrgAdmin->FEFFDT = $orgAdminInDb->FEFFDT;
                    }
                    if (StringUtil::isNullOrWhiteSpace($newOrgAdmin->FLEFFDT)){
                        $newOrgAdmin->FLEFFDT = $orgAdminInDb->FLEFFDT;
                    }

                    $totalResult->addSubResult($api->updateOrgAdmin($newOrgAdmin, $orgAdminInDb));
                }
                $this->executeWriteBackHandlerWithTotal($totalResult, $totalCount, $writeBackHandler);
            }
        }
        return $totalResult;
    }
}